import React, { useEffect, useRef } from "react"
import { Form, Input, Modal, FormInstance, ModalProps } from "antd"

const useResetFormOnCloseModal = ({
  form,
  visible
}: {
  form: FormInstance
  visible?: boolean
}) => {
  const prevVisibleRef = useRef<boolean>()

  useEffect(() => {
    prevVisibleRef.current = visible
  }, [visible])
  const prevVisible = prevVisibleRef.current

  useEffect(() => {
    if (!visible && prevVisible) {
      form.resetFields()
    }
  }, [visible])
}

const ModalForm: React.FC<ModalProps> = ({ visible, onCancel }) => {
  const [form] = Form.useForm()

  useResetFormOnCloseModal({
    form,
    visible
  })

  const onOk = () => {
    form.submit()
  }

  const changeVal = (e) => {
    console.log("changeVal", e)
  }

  return (
    <Modal
      title="Basic Drawer"
      visible={visible}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
        name="userForm"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input onChange={changeVal} />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default ModalForm
